﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Data;
using System.Linq;
namespace Phone.Framework.Behaviors
{

    public class HighlightTextBehavior : Behavior<TextBlock>
    {
        private void MarkSearchWord(string searchText, string word)
        {
            if (word.Length >= searchText.Length && word.StartsWith(searchText))
            {

                AssociatedObject.Text = string.Empty;
                var bold = new Bold();
                bold.Inlines.Add(new Run() { Text = searchText });
                AssociatedObject.Inlines.Add(bold);
                AssociatedObject.Inlines.Add(new Run { Text = word.Substring(searchText.Length) });
            }
            else
            {
                AssociatedObject.Text = word;
            }
        }
        protected override void OnAttached()
        {
            AssociatedObject.Loaded += new RoutedEventHandler(AssociatedObject_Loaded);
            //BindingOperations.SetBinding(this, ItemsSourceProperty, 
            //    new Binding("ItemsSource") { Source = AssociatedObject, Mode = BindingMode.TwoWay });
            base.OnAttached();
        }

        void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
        {
            word = AssociatedObject.Text;
            MarkSearchWord(Key, word);
        }

        private string word;



        public string Key
        {
            get { return (string)GetValue(KeyProperty); }
            set { SetValue(KeyProperty, value); }
        }

     
        public static readonly DependencyProperty KeyProperty =
            DependencyProperty.Register("Key", typeof(string), typeof(HighlightTextBehavior), 
            new PropertyMetadata(string.Empty));

        


    }
}
